package server;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import client.IFrame;

public class TxRxS {

	int portNumber;
	ObjectInputStream ois;
	ObjectOutputStream oos;
	ServerSocket socket;
	
	public TxRxS(int newListenPort)
	{
		portNumber=newListenPort;
		try
		{
			socket=new ServerSocket(portNumber);
			if(socket==null)
			{
				System.out.println("socket is null...");
			}
		}
		catch(IOException e)
		{
			//don't do much I suppose....
		}
	}
	
	public void listenOnce()
	{		
		try 
		{
			//accept() will block until a client connects
	        System.out.println("Waiting for connections.");
			Socket client = socket.accept();
			connect(client);
		} 
		catch (IOException e) 
		{
			//
			System.out.println("Call to ServerSocket with port number " + portNumber + " failed...");
		}
	}
	
	public void connect(Socket client)
	{
		IFrame currentFrame=null;
		System.out.println("Connecting to client: " + client.getInetAddress());
		try
		{
			ois = new ObjectInputStream(client.getInputStream());
			oos = new ObjectOutputStream(client.getOutputStream());
		}
		catch(IOException e)
		{
			//Add something here...
		}
		
	}
	
	public IFrame readData()
	{
		
		
		try
		{
			IFrame frame=new IFrame();
			frame=(IFrame)ois.readObject();
			//frame=(IFrame)ois.readObject();
			return frame;
		}
		catch(IOException e)
		{
			System.out.println("Something went wrong when reading from socket IO exception...");
			return new IFrame();
		}
		catch(ClassNotFoundException e)
		{
			System.out.println("Something went wrong when reading from socket, class not found...");
			return new IFrame();
		}
		
		
	}
	
	public void sendACK(IFrame ackFrame)
	{
		try
		{
			oos.writeObject(ackFrame);
			//oos.flush();
		}
		catch(IOException e)
		{
			//nothing...-___-;
		}
	}
	

	
	public void closeConnection()
	{
		try
		{
			ois.close();
			oos.close();
		}
		catch(IOException e)
		{
			//do something here maybe...
		}
	}
	
}
